package com.haliyoo.adhere.widget;

import java.io.ByteArrayOutputStream;
import java.util.List;

import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.ImageItem;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.activity.CreativeDesignActivity;
import com.haliyoo.adhere.bean.WeiboBean;
import com.haliyoo.adhere.controller.AdUserConstant;
import com.haliyoo.adhere.controller.Constants;
import com.haliyoo.adhere.controller.OAuthConstant;
import com.haliyoo.adhere.util.BitmapGet;
import com.haliyoo.adhere.widget.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public abstract class LocalWeiboLayout {
	private static String TAG = "LocalWeiboLayout";
	private Context context = null;
	private static List<WeiboBean> wbList = null;
	ProgressBar pbRefresh = null;
	ProgressBar pbMore = null;

	protected LocalWeiboLayout(Context context) {
		// TODO Auto-generated constructor stub
		this.context = context;
	}

	/**
	 * 刷新微博列表
	 */
	public void refreshWeiboList() {

        //建立新一个新的线程下载图片
        new Thread() {
            @Override
            public void run() {
            	Message message = null;
            	
                /// 获取微博列表
                wbList = onGetWeiboList();
            	
            	/// 发送显示微博的消息
                message = handler.obtainMessage(Constants.SHOW_NEW_WEIBO_CONTENT, wbList);
                handler.sendMessage(message);
            }
        }.start();
	}

	/// 发消息加载微博列表
    Handler handler = new Handler() {
        public void handleMessage(Message message) {
        	/// 显示微博
        	if (message.what == Constants.SHOW_NEW_WEIBO_CONTENT){
        		if (message.obj != null) {
    				WeiBoAdapater adapater = new WeiBoAdapater();
    				ListView weibolist = (ListView) ((Activity) context).findViewById(R.id.LIST_VIEW_LOCAL_WEIBO);
    				weibolist.setOnItemClickListener(new OnItemClickListener() {

    					public void onItemClick(AdapterView<?> arg0, View view,
    							int arg2, long arg3) {

    						/// 显示微博内容
    						onShowWeiboDetail(arg0, view, arg2, arg3);
    					}

    				});
    				weibolist.setAdapter(adapater);
    			} else {
    				Toast.makeText(context, R.string.STR_NONE_WEIBO_UPDATE, Toast.LENGTH_SHORT).show();
    			}
        	}
        }
    };
    
	public class WeiboHolder {
		public ImageView wbicon = null;
		public TextView wbtime = null;
		public TextView wbtext = null;
		public ImageView wbloc = null;
		public WeiboBean weibo = null;
	}

	// 微博列表Adapater
	public class WeiBoAdapater extends BaseAdapter {

		public int getCount() {
			return wbList.size();
		}

		public Object getItem(int position) {
			return wbList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = LayoutInflater.from(context.getApplicationContext()).inflate(
					R.layout.local_weibo, null);
			final WeiboHolder wh = new WeiboHolder();
			wh.wbtext = (TextView) convertView.findViewById(R.id.TEXT_VIEW_TEXT);
			wh.wbtime = (TextView) convertView.findViewById(R.id.TEXT_VIEW_TIME);
			wh.wbicon = (ImageView) convertView.findViewById(R.id.IMAGE_VIEW_PIC);
			wh.wbloc = (ImageView) convertView.findViewById(R.id.IMAGE_VIEW_LOCATION);
			wh.weibo = wbList.get(position);
			if (wh.weibo != null) {
				convertView.setTag(wh.weibo.getId());
				if (wh.weibo.getTime() != null){
					wh.wbtime.setText(wh.weibo.getTime().toLocaleString());
				}
				if (wh.weibo.getText() != null){
					SpannableString ss = FaceManager.getInstance().convertTextToEmotion(context, wh.weibo.getText());
					wh.wbtext.setText(ss);
//					wh.wbtext.setText(wh.weibo
//							.getText(), TextView.BufferType.SPANNABLE);
				}
				if (wh.weibo.getExistImage()){
					if (wh.weibo.getIcon() != null){
						wh.wbicon.setImageBitmap(BitmapGet.imageZoomByHeight(wh.weibo.getIcon(), Constants.THUMB_IMAGE_HEIGHT));
					} else if (wh.weibo.getIconUrl() != null){
						AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
	                    if(wh.weibo.getIconUrl() !=null){
	                        String picurl = wh.weibo.getIconUrl();

	                        Drawable cachedImage = asyncImageLoader.loadDrawable(picurl, wh.wbicon, 
	                        		new ImageCallback(){
	                            public void imageLoaded(Drawable imageDrawable,
	                            		ImageView imageView, String imageUrl) {
	                                showImg(imageView,imageDrawable, Constants.THUMB_IMAGE_HEIGHT);
	                            }
	                        });
	                        if (cachedImage == null) 
	                        {
	                        	wh.wbicon.setImageResource(R.drawable.icon);
	                        }
	                        else
	                        {
	                            showImg(wh.wbicon, cachedImage, Constants.THUMB_IMAGE_HEIGHT);
	                        }
	                    }
					}
				}
				if (wh.weibo.getExistLocation()) {
					wh.wbloc.setVisibility(View.VISIBLE);
				} else {
					wh.wbloc.setVisibility(View.GONE);
				}
			}
			
			/// 发布键功能
			Button btPublish = (Button) convertView.findViewById(R.id.BUTTON_PUBLISH);
			btPublish.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					final long weiboId = AdUserConstant.getInstance().publish(
							context, wh.weibo);
					if (weiboId > 0) {
						Toast.makeText(context,
								R.string.STR_PUBLISH_SUCCESSFULLY,
								Toast.LENGTH_SHORT).show();
						
						/// 上传到AdHere服务器
				        new Thread() {
				            @Override
				            public void run() {
				        		/// 获取数目
				            	if (AdUserConstant.getInstance().post(AdUserConstant.getInstance().user, 
				            			new Long(weiboId).toString(),
				            			AdUserConstant.getInstance().sign) == 1) {
				            		Log.i(TAG, "post to AdHere Server Successfully.");
				            	}
				            }
				        }.start();
					} else {
						Toast.makeText(context,
								R.string.STR_PUBLISH_FAILED, Toast.LENGTH_SHORT)
								.show();
					}
				}
			});

			/// 编辑键功能
			Button btEidt = (Button) convertView.findViewById(R.id.BUTTON_EDIT);
			btEidt.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					onShowWeiboDetail(wh.weibo);
				}
			});
			
			return convertView;
		}
	}

	/**
	 * 显示图片
	 * @param view 容器
	 * @param img 图像
	 */
	private void showImg(ImageView view, Drawable img, int height){
        //获取这个图片的宽和高
        int owidth = img.getIntrinsicWidth();
        int oheight = img.getIntrinsicHeight();
         
        //定义预转换成的图片的宽和高
        int newHight = height;
        int newWidth = (newHight * owidth) / oheight;

        LayoutParams para = (LayoutParams) view.getLayoutParams();
        para.width = newWidth;
        para.height = newHight;
        
        view.setLayoutParams(para);
        
        view.setImageDrawable(img);
    }
	
	public static WeiboBean getWeiboBean(String dbId) {
		for (WeiboBean wb : wbList) {
			if (wb.getId().equals(dbId)) {
				return wb;
			}
		}
		
		return null;
	}
	
	public static List<WeiboBean> getWeiboList() {
		return wbList;
	}

	/**
	 * 获取微博列表
	 * @return 微博列表
	 */
	public abstract List<WeiboBean> onGetWeiboList();
	
	/**
	 * 显示微博细节
	 * @param arg0 The AdapterView where the click happened.
	 * @param view The view within the AdapterView that was clicked (this will be a view provided by the adapter)
	 * @param arg2 The position of the view in the adapter.
	 * @param arg3 The row id of the item that was clicked.
	 */
	public abstract void onShowWeiboDetail(AdapterView<?> arg0, View view,
			int arg2, long arg3);
		
	/**
	 * 显示微博细节
	 * @param weiboBean 微博内容
	 */
	public abstract void onShowWeiboDetail(WeiboBean weiboBean);
	
	/**
	 * 完成发布事件
	 * @param weiboBean 微博
	 */
	public abstract void onFinishedPublish(WeiboBean weiboBean);
}
